package com.leha.forum.lehare.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leha.forum.lehare.entity.Permission;
import com.leha.forum.lehare.entity.RolePermission;
import com.leha.forum.lehare.service.PermissionService;
import com.leha.forum.lehare.service.RolePermissionService;
import com.leha.forum.lehare.mapper.RolePermissionMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【role_permission】的数据库操作Service实现
* @createDate 2025-04-15 21:44:28
*/
@Service
public class RolePermissionServiceImpl extends ServiceImpl<RolePermissionMapper, RolePermission>
    implements RolePermissionService{


    @Override
    public boolean deleteByRoleId(Integer roleId) {
        if (roleId <= 0) {
            throw new IllegalArgumentException("角色 ID 无效");
        }

        return remove(new QueryWrapper<RolePermission>().eq("role_id", roleId));
    }

    @Override
    public boolean deleteByPermissionId(Integer permissionId) {
        if (permissionId <= 0) {
            throw new IllegalArgumentException("权限 ID 无效");
        }

        return remove(new QueryWrapper<RolePermission>().eq("permission_id", permissionId));
    }

    @Override
    public List<Permission> getRolePermissions(Integer roleId, PermissionService permissionService) {
        if (roleId <= 0) {
            throw new IllegalArgumentException("角色 ID 无效");
        }

        List<RolePermission> relations = list(new QueryWrapper<RolePermission>().eq("role_id", roleId));
        return relations.stream().map(e -> permissionService.getById(e.getPermissionId())).collect(Collectors.toList());
    }

    @Override
    public boolean bindPermission(Integer roleId, Integer permissionId) {
        if (roleId <= 0) {
            throw new IllegalArgumentException("角色 ID 无效");
        }

        if (permissionId <= 0) {
            throw new IllegalArgumentException("权限 ID 无效");
        }

        if (getOne(new QueryWrapper<RolePermission>().eq("role_id", roleId).eq("permission_id", permissionId)) != null) {
            return true;
        } else {
            return save(new RolePermission(roleId, permissionId));
        }
    }

    @Override
    public boolean unbindPermission(Integer roleId, Integer permissionId) {
        if (roleId <= 0) {
            throw new IllegalArgumentException("角色 ID 无效");
        }

        if (permissionId <= 0) {
            throw new IllegalArgumentException("权限 ID 无效");
        }

        return remove(new QueryWrapper<RolePermission>().eq("role_id", roleId).eq("permission_id", permissionId));
    }
}




